<?php
/**
 * Smart Library - Smart Framework
 * http://smart-framework.highet.eu
 *
 * @category   SmartL
 * @package    SmartL_DataBinder
 * @subpackage DataAdapter
 * @copyright  Copyright (c) 2005-2008 Smart Framework team - Stepan Sindelar, Vojtech Vit
 * @license    http://www.opensource.org/licenses/bsd-license.php	New BSD License
 */

/**
 * @see SmartL_DataBinder_DataAdapter_Abstract
 */
require_once 'SmartL/DataBinder/DataAdapter/Abstract.php';

/**
 * DataAdapter for arrays.
 * 
 * Examples of data binding on this adapter:
 * <code>
 *		in binding rules: 'price' 
 *		result: $array['price']
 *		
 *		in binding rules: array('price','vat')
 *		result: $array['price']['vat']
 * </code>
 *
 * @package SmartL_DataBinder
 * @subpackage DataAdapter
 */
class SmartL_DataBinder_DataAdapter_Array extends SmartL_DataBinder_DataAdapter_Abstract {
	/** 
	 * @param string|array $name
	 * @param mixed $value
	 * @param mixed $array
	 * @return mixed
	 */
	public function _walk($name, $value = null, &$array = null) {
		//If the name is string,...
		if (is_string ( $name )) {
			//...it is the index and value is inserted/returned under this index
			if ($value !== null) {
				$array [$name] = $value;
			}
			return $array [$name];
		} else if (is_array ( $name )) {
			//if it is array, method walks trough this array
			//get first value from array = next index in our array that is being set up
			reset ( $name );
			$nameFirstKey = key ( $name );
			$nameFirst = $name [$nameFirstKey];
			unset ( $name [$nameFirstKey] );
			//was it also last value in it?
			if (count ( $name ) === 0) {
				//if so, insert/return value under the index
				if ($value !== null) {
					$array [$nameFirst] = $value;
				}
				return $array [$nameFirst];
			} else {
				//if not, recursively walk trough array
				//$array[$nameFirst] = null;
				return $this->_walk ( $name, $value, $array [$nameFirst] );
			}
		} else {
			require_once 'SmartL/DataBinder/DataAdapter/Array/Exception.php';
			throw new SmartL_DataBinder_DataAdapter_Array_Exception ( "Supported names are only arrays and strings." );
		}
	}
	
	/**
	 * @param string|array $name
	 * @param mixed $value
	 */
	public function set($name, $value) {
		$this->_walk ( $name, $value, $this->getObject () );
	}
	
	/**
	 * @param string|array $name
	 * @return mixed
	 */
	public function get($name) {
		return $this->_walk ( $name, null, $this->getObject () );
	}
}
